﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Web;
using System.Web.Http;
using We7.Framework.Util;
using XQ.RequestOfficeSupplies.DAL;
using XQ.RequestOfficeSupplies.DAL.DAL.Common;
using XQ.RequestOfficeSupplies.DAL.Models;
using XQ.RequestOfficeSupplies.WebAPI.Common;
using XQ.RequestOfficeSupplies.WebAPI.Filter;

namespace XQ.RequestOfficeSupplies.WebAPI.Controllers.System
{
    /// <summary>
    /// 上传API（部分验证Token）
    /// </summary>
    [FormAuthenticationFilter]
    public class UploadController : ApiController
    {
        /// <summary>
        /// 通用单上传（不存Upload表）
        /// </summary>
        /// <returns></returns>
        [Route("Api/Upload/UploadFile")]
        [HttpPost]
        [AllowAnonymous]
        public Upload UploadFile()
        {
            return UploadFile("", "", "File", false);
        }

        /// <summary>
        /// 多上传照片
        /// </summary>
        /// <param name="tableName">表名</param>
        /// <param name="signName">标识名</param>
        /// <returns></returns>
        [Route("Api/Upload/UploadImg")]
        [HttpPost]
        [AllowAnonymous]
        public Upload UploadImg(string tableName, string signName)
        {
            return UploadFile(signName, tableName, "Images", true);
        }

        /// <summary>
        /// 多上传文件
        /// </summary>
        /// <param name="tableName">表名</param>
        /// <param name="signName">标识名</param>
        /// <returns></returns>
        [Route("Api/Upload/UploadAnnex")]
        [HttpPost]
        public Upload UploadAnnex(string tableName, string signName)
        {
            return UploadFile(signName, tableName, "Annex", false);
        }

        /// <summary>
        /// 上传文件方法
        /// </summary>
        /// <param name="signname">标识名</param>
        /// <param name="tableName">表名</param>
        /// <param name="fileFolder">上传文件夹</param>
        /// <param name="isPic">是否为照片</param>
        /// <returns></returns>
        private Upload UploadFile(string signname, string tableName, string fileFolder, bool isPic)
        {
            try
            {
                LogBll.Instance.WriteLog(LogBll.LogType.Other, "", 0, "上传开始", "", "", "", signname);
                //获取用户信息
                TokenModel token = TokenHelper.GetTokenByHeaders(Request.Headers);

                HttpContextBase context = (HttpContextBase)Request.Properties["MS_HttpContext"];
                HttpRequestBase request = context.Request;
                string fileExName = Path.GetExtension(request.Files[0].FileName);
                List<string> exNames = new List<string> { ".jpg", ".jpeg", ".png", ".doc", ".docx" };
                bool isAllow = exNames.Contains(fileExName);
                if (!isAllow)
                {
                    return null;
                }
                string filename = DateTime.Now.ToString("yyyyMMddHHmmssfff")+ token.UID + fileExName;
                string uploadPath = HttpContext.Current.Server.MapPath(string.Format("~/{0}", "Upload/" + fileFolder)) + "\\";

                //不存在就创建目录
                if (!Directory.Exists(uploadPath))
                {
                    Directory.CreateDirectory(uploadPath);
                }
                //如果是图片就压缩大小，文件就直接保存
                if (isPic)
                {
                    string tempFilePath = uploadPath + "_temp" + filename;
                    request.Files[0].SaveAs(tempFilePath);
                    Thread.Sleep(100);
                    ImageUtils.MakeThumbnail(tempFilePath, uploadPath + filename, 800, 0, "W", ".jpg");
                    Thread.Sleep(20);
                    File.Delete(tempFilePath);
                }
                else
                {
                    request.Files[0].SaveAs(uploadPath + filename);
                }

                LogBll.Instance.WriteLog(LogBll.LogType.Other, "", 0, "上传完成", "", "", "", signname);
                Upload upload = new Upload();
                upload.tableName = tableName;
                upload.signName = signname;
                upload.OldFileName = request.Files[0].FileName;
                upload.NewFileName = filename;
                upload.Path = "/Upload/" + fileFolder;
                upload.UploadTime = DateTime.Now;
                upload.UploadUserID = token.UID;
                return upload;
            }
            catch (Exception ex)
            {
                LogBll.Instance.WriteErrLog("",0, "上传出错", "", "", "", ex.Message,"","","");
                return null;
            }
        }
    }
}
